#include "../ExEngine/input/dinput.h"
#include "../ExEngine/render/d3d.h"
#include "../ExEngine/engine/engine.h"
#include "scene.h"

float lastCameraX = 0;

int GetPostionKey()
{
	Vector3f cameraPosition = CEngine::GetInstance()->GetCamera()->getPosition();
	int cameraPosIdx = (int)(cameraPosition.x / 26.17f);
	return cameraPosIdx;
}

HRESULT UpdateDemo(const float dt)
{
	Vector3f cameraPosition = CEngine::GetInstance()->GetCamera()->getPosition();

	int cameraPositionKey = GetPostionKey();

	for(int i = 0; i < g_tunnel.TableKeyCount(); i++)
	{
		int key = g_tunnel.KeyAtTableIndex(i);
		if(key < cameraPositionKey - (TUNNEL_RANGE / 2) || key > cameraPositionKey + (TUNNEL_RANGE / 2))
		{
			TunnelSegement *pSegment = g_tunnel.DataAtIndex(i)[0];
			pSegment->Release();
			g_tunnel.Remove(key);
			i = 0;
		}

	}

	for(int i = cameraPositionKey - (TUNNEL_RANGE / 2), j = 0; i < cameraPositionKey + (TUNNEL_RANGE / 2); i++, j++)
	{
		if(g_tunnel.KeyElementCount(i) == 0)
		{
			TunnelSegement* t = EE_NEW TunnelSegement();
			t->Create(Vector3f(26.17 * i, 0,0));
			g_tunnel.Add(i,t);
		}
		
		TunnelSegement *pSegment = g_tunnel.DataAtIndex(j)[0];
		pSegment->Update(dt);
		pSegment->Draw();
	}


	lastCameraX = cameraPosition.x;
		

	if (SHOW_TRAINS)
	{
		g_train.Draw();
		g_train.Update(dt);
		g_train.SetVelocity(400);
	}

	lightManager.Draw();
	lightManager.Update(dt);
	
	if(CEngine::GetInstance()->GetInput()->isKeyReleased(DIK_R))
		CEngine::GetInstance()->GetRenderer()->ReloadResources(CD3D9Device::RESOURCE_ALL);

	

	if(CEngine::GetInstance()->GetInput()->isKeyReleased(DIK_X))
	{
		if(CEngine::GetInstance()->GetRenderer()->GetRenderMode() != CD3D9Device::RenderMode::DEFAULT)
			CEngine::GetInstance()->GetRenderer()->SetRenderMode(CD3D9Device::RenderMode::DEFAULT);
		else
			CEngine::GetInstance()->GetRenderer()->SetRenderMode(CD3D9Device::RenderMode::LIGHTING);
	}

	return S_OK; 
}
